package com.wzy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class IndexController {

    @GetMapping({"/index","/"})
    public String index(){
        return "index";
    }

    @GetMapping("/main")
    public String main(Model model, HttpServletRequest request){
        model.addAttribute("shiroSession",SecurityUtils.getSubject().getSession().getId());
        model.addAttribute("servletSession",request.getSession().getId());
        return "main";
    }

    @RequiresRoles("USER")
    @GetMapping("/user")
    public String user(){
        return "user";
    }

    @RequiresRoles("ADMIN")
    @GetMapping("/admin")
    public String admin(){
        return "admin";
    }

    @GetMapping("/unauthorized")
    public String unauthorized(){
        return "403";
    }

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(Model model,String username, String password
            , @RequestParam(defaultValue = "false") Boolean rememberMe){
        //获取subject
        Subject subject = SecurityUtils.getSubject();

        //创建用户名/密码身份验证Token（即用户身份/凭证）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,rememberMe);

        try {
            //登录，其会自动委托给 SecurityManager.login 方法进行登录；
            subject.login(token);
        } catch (UnknownAccountException e){
            model.addAttribute("errMsg","错误的帐号");
            return "/login";
        } catch (IncorrectCredentialsException e){
            model.addAttribute("errMsg","错误的凭证");
            return "/login";
        } catch (Exception e){
            model.addAttribute("errMsg",e.getMessage());
            return "/login";
        }

        return "redirect:/main";
    }

    @GetMapping("/logout")
    public String logout(){
        //获取subject
        Subject subject = SecurityUtils.getSubject();
//        判断是否已经登录
        if (subject.getPrincipal()!=null){
            subject.logout();
        }
        return "redirect:/index";
    }
}
